﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using Newtonsoft.Json.Linq;

namespace QW.Found.JwtAuthorize
{
    /// <summary>
    /// 令牌构建器
    /// </summary>
    public class TokenBuilder : ITokenBuilder
    {
        private readonly JwtAuthorizationRequirement jwtAuthorizationRequirement;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jwtAuthorizationRequirement"></param>
        public TokenBuilder(JwtAuthorizationRequirement jwtAuthorizationRequirement)
        {
            this.jwtAuthorizationRequirement = jwtAuthorizationRequirement;
        }

        /// <summary>
        /// 构建令牌
        /// </summary>
        /// <param name="claims"></param>
        /// <param name="expires"></param>
        /// <param name="notBefore">此时间后才会生效</param>
        /// <returns></returns>
        public TokenInfo BuildJwtToken(IEnumerable<Claim> claims, DateTime expires, DateTime? notBefore = null)
        {
            var jwt = new JwtSecurityToken(
                issuer: jwtAuthorizationRequirement.Issuer,
                audience: jwtAuthorizationRequirement.Audience,
                claims: claims.ToArray(),
                notBefore: notBefore,
                expires: expires,
                signingCredentials: jwtAuthorizationRequirement.SigningCredentials
            );
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            //加密jwtToken 在使用的时候需要先解密
            // encodedJwt = AESCryptoHelper.Encrypt(encodedJwt);

            var responseJson = new TokenInfo
            {
                TokenValue = encodedJwt,
                Expires = expires,
                Scheme = jwtAuthorizationRequirement.Scheme
            };
            return responseJson;
        }
    }
}
